package com.uxsino.commons.logicSelector.propFunction;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PropMethodValueFunction implements IPropValueFunction {

    private static Logger logger = LoggerFactory.getLogger(PropMethodValueFunction.class);

    private Method method;

    private Class<?> indexType;

    private Object index;

    public PropMethodValueFunction(Method method) {
        this.method = method;
        Class<?>[] params = method.getParameterTypes();
        if (params.length > 1)
            throw new IllegalArgumentException(
                "can not set this method as prop for it has more than one parameters: " + method.getName());
        if (params.length == 1)
            indexType = params[0].getClass();
        else
            indexType = null;
    }

    @Override
    public Object get(Object object) {

        try {
            if (indexType != null) {
                return method.invoke(object, index);
            } else {
                return method.invoke(object);
            }
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            logger.error("error getting property.", e);
        }
        return null;
    }

    public void setIndex(String index) {
        this.index = index;

        if (indexType.isAssignableFrom(Integer.class)) {
            this.index = Integer.parseInt(index);
        } else
            this.index = index;
    }

    public boolean isIndexed() {
        return indexType != null;
    }
}
